package com.lnb.redis.config;

import cn.hutool.core.util.StrUtil;
import com.lnb.redis.properties.RedisProperties;
import lombok.extern.log4j.Log4j2;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Log4j2
@Configuration
public class RedissonConfig {

    @Bean
    @ConditionalOnMissingBean
    public RedisProperties redisProperties() {
        return new RedisProperties();
    }

    @Bean
    public RedissonClient redissonClient(final RedisProperties properties) {
        log.info("==== 初始化Redisson ==== Client==Host={},Port={}", properties.getHost(), properties.getPort());
        Config config = new Config();
        String redisAddress = String.format("redis://%s:%s", properties.getHost(), properties.getPort());
        SingleServerConfig singleServerConfig = config.useSingleServer();
        singleServerConfig
                .setAddress(redisAddress);
        if(StrUtil.isNotEmpty(properties.getPassword())){
            singleServerConfig.setPassword(properties.getPassword());
        }
        singleServerConfig.setDatabase(properties.getDatabase());
        RedissonClient client = Redisson.create(config);
        log.info("==== redissonClient 连接成功 ==== host:{}, port:{}", properties.getHost(), properties.getPort());
        return client;
    }
}
